package com.bbx.taxi.client.Activity.Order;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.InjectView;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.official.passanger.Return.Officail_OrderInfo;
import com.bbx.api.sdk.model.official.passanger.Return.Official_VclassInfo;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OfficialOrderList;
import com.bbx.api.sdk.model.official.passanger.Return.OrderList.OfficialPriceDetail;
import com.bbx.api.sdk.model.passanger.OrderDetailBuild;
import com.bbx.api.sdk.model.passanger.Return.CancelReasonList;
import com.bbx.api.sdk.model.passanger.Return.OrderDetails;
import com.bbx.api.sdk.model.passanger.Return.CancelReasonList.CancelReason;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.OrderDetailNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.taxi.client.Task.MyStarTask;
import com.bbx.taxi.client.Task.MyStarTask.OnStarListener;
import com.bbx.taxi.client.Task.MyVclassInfoTask;
import com.bbx.taxi.client.Task.MyVclassInfoTask.OnVclassInfoListener;
import com.bbx.taxi.client.Task.OrderDetailTask;
import com.bbx.taxi.client.Task.OrderDetailTask.OnOrderDetailFinishListener;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.official.R;
import com.bbx.taxi.client.Activity.MainActivity;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Attribute.MainAttribute;
import com.bbx.taxi.client.Bean.Extra.MainMsg;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.MyOrder.OrderCencelDB;
import com.bbx.taxi.client.Task.CancelReasonListTask;
import com.bbx.taxi.client.Task.CancelReasonListTask.OnFinishListener;
import com.bbx.taxi.client.Util.DateFormat;
import com.bbx.taxi.client.Util.FormatUtil;
import com.bbx.taxi.client.Util.OrderDetialToOrderList;
import com.bbx.taxi.client.Util.Tel;

public class OrderCancelReason extends BaseBBXActivity implements OnOrderDetailFinishListener,OnVclassInfoListener,
		OnFinishListener,OnStarListener {
	@InjectView(R.id.sliding_card_content_view)
	RelativeLayout sliding_card_content_view;
	@InjectView(R.id.layout_service)
	LinearLayout layout_driver;
	@InjectView(R.id.layout_detail)
	RelativeLayout layout_detail;
	/** 司机名称 */
	@InjectView(R.id.tv_driver_name)
	TextView tv_driver_name;
	/** 车牌号 */
	@InjectView(R.id.tv_car_No)
	TextView tv_car_No;
	/** 时间 */
	@InjectView(R.id.tv_time)
	TextView tv_time;
	/** 订单类型 */
	@InjectView(R.id.order_type)
	TextView tv_order_type;
//	/** 人数 */
//	@InjectView(R.id.tv_count)
//	TextView tv_count;
	/** 出发地 */
	@InjectView(R.id.tv_start)
	TextView tv_start;
	/** 目的地 */
	@InjectView(R.id.tv_end)
	TextView tv_end;
	@InjectView(R.id.tv_reason)
	TextView tv_reason;
	@InjectView(R.id.btn_confirm)
	Button btn_confirm;
	@InjectView(R.id.tv_rating)
	TextView tv_rating;
	@InjectView(R.id.rb_rating)
	RatingBar rb_rating;
	@InjectView(R.id.ib_sjtel)
	ImageButton ib_sjtel;
	@InjectView(R.id.layout_estimate_price)
	RelativeLayout layout_estimate_price;
	@InjectView(R.id.tv_estimate_price)
	TextView tv_estimate_price;
	@InjectView(R.id.tv_price_left)
	TextView tv_price_left;
	@InjectView(R.id.iv_own)
	ImageView iv_own;
	private MyOrderDB db_myorder;// 我的订单数据库
	private OrderCencelDB db_cencel;// 取消订单数据库
	private OfficialOrderList mOfficialOrderList;
	OfficialPriceDetail price_detail=null;
	private String order_id;
	private String reason;
	private int order_type;
	private int viewId;
	private OrderDetailTask mOrderDetailTask;
	private CancelReasonListTask mCancelReasonListTask;
	private List<CancelReason> list;

	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_cancel_reason);
		super.onCreate(savedInstanceState);
		
	}

	@Override
	protected void initView() {
		setTitle(true, getString(R.string.order_detail), -1, getString(R.string.complaint));
		db_myorder = new MyOrderDB(this);
		db_cencel = new OrderCencelDB(this);
		btn_confirm.setOnClickListener(this);
		sliding_card_content_view.setVisibility(View.GONE);
		ib_sjtel.setVisibility(View.GONE);
		list=new ArrayList<CancelReason>();
		setCancelReason();
		try {
			initView2();
			onLoadDate();
		} catch (Exception e) {
			onLoadDate();
		}
	}

	public void initView2() {
		Intent intent = getIntent();
		if (intent.getExtras() != null) {
			order_id = intent.getExtras().getString(OrderMsg.extra_order_id);
		} else {
			ToastUtil.showToast(context, R.string.error);
			finish();
			return;
		}
		new AsyncTask<Void, Void, Void>(){
			@Override
			protected Void doInBackground(Void... params) {
				mOfficialOrderList = db_myorder.onReadDB(context, order_id);
				reason = db_cencel.onGetReason(order_id);
				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				if (reason == null || reason.equals("")) {
					tv_reason.setText(R.string.order_canceled);
				} else {
					int status=Integer.parseInt(mOfficialOrderList.getOrder_status());
					if (status== Value.ORDER_STATUS_KF_CANCEL) {
						tv_reason.setText(getString(R.string.order_canceled) + "\n"
								+ String.format(getString(R.string.reason), reason));
					} else {
						tv_reason.setText(String.format(
								getString(R.string.cancel_reason), reason));
					}
					setView();
				}
				super.onPostExecute(result);
			}
		    	
		}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub

	}
	public void setView(){
		MyVclassInfoTask.getInstance(context, mOfficialOrderList.getTcId(), mOfficialOrderList.getVehicle_id()).setOnVclassInfoListener(this);
		if(mOfficialOrderList.getDriver_id()!=null&&!mOfficialOrderList.getDriver_id().equals("")){
			tv_driver_name.setText(mOfficialOrderList.getDriver_name());
			tv_car_No.setText(mOfficialOrderList.getCar_NO());
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(1);// 保留小数点1位
			tv_rating.setText(FormatUtil.onFormatStar((float) mOfficialOrderList
					.getDriver_star()) + "");
			rb_rating.setRating(FormatUtil.onFormatStar((float) mOfficialOrderList
					.getDriver_star()));
			MyStarTask.getInstance(context, order_id, mOfficialOrderList.getDriver_id()).setOnStarListener(this);
			layout_driver.setVisibility(View.VISIBLE);
			layout_detail.setVisibility(View.GONE);
		}else{
			layout_driver.setVisibility(View.GONE);
			layout_detail.setVisibility(View.VISIBLE);
		}
        //价格
		if(price_detail!=null){
			layout_estimate_price.setVisibility(View.VISIBLE);
			tv_estimate_price.setText(FormatUtil.onFormatPrice(price_detail.getCancelPrice()));
			tv_estimate_price.setVisibility(View.VISIBLE);
			tv_price_left.setText("消单费");
		}
		
		
		
		//由于时间容易出现空
		if(mOfficialOrderList==null){
			onLoadDate();
			return;
		}
		tv_time.setText(DateFormat.onDateRemove_ss(mOfficialOrderList
				.getAppoint_time()));
		order_type =Integer.parseInt(mOfficialOrderList.getOrder_type()) ;
		switch (order_type) {
		case Value.ORDER_TYPE_SN:
			tv_order_type.setText(R.string.sn);
			viewId = Value.VIEWID_SN;
//			tv_count.setVisibility(View.GONE);
			break;
		case Value.ORDER_TYPE_KJ:
			tv_order_type.setText(R.string.kj);
			viewId = Value.VIEWID_KJ;
//			tv_count.setText(String.format(getString(R.string.num_jian),
//					mOfficialOrderList.getOrderDetail().getCount()));
			break;
		case Value.ORDER_TYPE_PC:
			tv_order_type.setText(R.string.pc);
			viewId = Value.VIEWID_PC;
//			tv_count.setText(String.format(getString(R.string.num),
//					mOfficialOrderList.getOrderDetail().getCount()));
			break;
		case Value.ORDER_TYPE_BC:
			tv_order_type.setText(R.string.bc);
//			tv_count.setText(String.format(getString(R.string.num_car),
//					mOfficialOrderList.getOrderDetail().getCount()));
			viewId = Value.VIEWID_BC;
			break;
		}
		tv_start.setText(mOfficialOrderList.getOrderDetail().getStart().getAddress());
		tv_end.setText(mOfficialOrderList.getOrderDetail().getEnd().getAddress());
		//判断自费类型
		try{
		if(Integer.parseInt(mOfficialOrderList.getOwn_expense())==Value.NOOWN){
		iv_own.setImageDrawable(context.getResources().getDrawable(R.drawable.icon_g));
		}else{
		iv_own.setImageDrawable(context.getResources().getDrawable(R.drawable.icon_z));
		}
		}catch(Exception e){}
		sliding_card_content_view.setVisibility(View.VISIBLE);
	}
     /**
     * 开始加载数据
     */
    public void onLoadDate(){
 		CancelReasonListTask.setOnFinishListener(this);
 		mCancelReasonListTask=CancelReasonListTask.getInstance(context, mApplication);
     }
	/**
	 * 设置本地的取消原因
	 */
	public void setCancelReason() {
		if (list != null) {
			list.clear();
			CancelReason mCancelReason = new CancelReasonList().new CancelReason();
			mCancelReason.setId(1);
			mCancelReason.setReason(this.getResources().getString(
					R.string.cancel_reason1));
			list.add(mCancelReason);
			mCancelReason = new CancelReasonList().new CancelReason();
			mCancelReason.setId(2);
			mCancelReason.setReason(this.getResources().getString(
					R.string.cancel_reason2));
			list.add(mCancelReason);
			mCancelReason = new CancelReasonList().new CancelReason();
			mCancelReason.setId(3);
			mCancelReason.setReason(this.getResources().getString(
					R.string.cancel_reason3));
			list.add(mCancelReason);
		}

	}

	/**
	 * 获取订单详情
	 */
	public void getOrderDetail(String order_id) {
		OrderDetailTask.getInstance(context, mApplication, order_id).setOnOrderDetailFinishListener(this);

	}

	/**
	 * 设置取消原因
	 */
	public void setOnCancelReason(int reason_id, String reason) {
		if (reason == null||reason.equals("")) {
			tv_reason.setText(R.string.order_canceled);
		} else if (reason_id == 0 && reason != null && reason.equals("")) {
			tv_reason.setText(R.string.order_canceled);
		} else {
			String type = "";
			for (int i = 0; i < list.size(); i++) {
				if (reason_id == list.get(i).getId()) {
					type = list.get(i).getReason();
					break;
				} else if (reason_id == (i + 1)) {
					type = list.get(i).getReason();
					break;
				}
			}
			int status=Integer.parseInt(mOfficialOrderList.getOrder_status());
			if ( status== Value.ORDER_STATUS_KF_CANCEL) {
				tv_reason.setText(getString(R.string.order_canceled) + "\n"
						+ String.format(getString(R.string.reason), reason));
			} else {
				tv_reason.setText(String.format(
						getString(R.string.cancel_reason),
						(type.equals("") ? "" : type + ";") + reason));
			}
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_right:
			Tel.onTel(context, Value.TEL_KF);
			break;
		case R.id.iv_left:
			finish();
			break;
		case R.id.btn_confirm:
			if(mOfficialOrderList.mOfficial_VclassInfo!=null){
			MainAttribute main = MainAttribute.getInstance();
			main.setAttribute(context,mOfficialOrderList);

			Intent intent = new Intent();
			intent.setClass(this, MainActivity.class);
			intent.putExtra(MainMsg.extra_viewpageId, viewId);
			intent.putExtra(MainMsg.extra_agin_xiadan, MainMsg.AGAIB_XIADAN);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 注意本行的FLAG设置
			startActivity(intent);}else{
				ToastUtil.showToast(context, R.string.try_again_later);
			}
			break;
		}
		super.onClick(v);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	public void finish() {
		setResult(resultCode, new Intent());
		super.finish();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onFinish() {
		String cancel_reason_json = SharedPreUtil.getStringValue(this,
				SharedPreEncryptUtil.cancel_reason_json, "");
		CancelReasonList mCancelReasonList = (CancelReasonList) new JsonBuild()
				.getData(CancelReasonList.class, cancel_reason_json);
		if (list != null && mCancelReasonList != null) {
			list.clear();
			list.addAll(mCancelReasonList.getList());
		}
		getOrderDetail(order_id);
	}

	@Override
	public void onOrderDetailFinish(Officail_OrderInfo mOfficail_OrderInfo) {
		if(mOfficail_OrderInfo!=null){
			int reason_id = 0;
					try{
						reason_id=Integer.parseInt(mOfficail_OrderInfo.getInfo().getReason_type());
					}catch(Exception e){}	
			String reason = mOfficail_OrderInfo.getInfo()
					.getCancel_reason();
			setOnCancelReason(reason_id, reason);
			mOfficialOrderList=mOfficail_OrderInfo.getInfo();
			//价格
			JSONObject json_price_detail = null;
			try {
				json_price_detail = new JSONObject(mOfficialOrderList.getPrice_Detail());
			} catch (JSONException e) {
				e.printStackTrace();
			}
		
			if(json_price_detail!=null){
			 price_detail = (OfficialPriceDetail) new JsonBuild().getData(OfficialPriceDetail.class,
					 json_price_detail.toString());
			}
			setView();
		}
		
	}

	@Override
	public void onVclassInfo(Official_VclassInfo mOfficial_VclassInfo,String class_id) {
		if(mOfficialOrderList.getVehicle_id().equals(class_id)){
		mOfficialOrderList.mOfficial_VclassInfo=mOfficial_VclassInfo;
		}
		
	}

	@Override
	public void onStarFinish(String order_id, int star) {
		tv_rating.setText(FormatUtil.onFormatStar((float)star) + "");
		rb_rating.setRating(FormatUtil.onFormatStar((float) star));
	}
}
